// dowmload.c
#include "common.h"
#include "uart.h"
#include "md5.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
extern uint8_t file_name[FILE_NAME_LENGTH];
uint8_t tab_1024[1024] = {
    0};
ota ota_data;

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

void set_ota_flag(int32_t Size)
{
    flash_erase(LL_FLASH_ERTYPE_PAGE, Ota_flag_Address);
    ota_data.ota_flag = 1;
    flash_program(Ota_flag_Address, ota_data.ota_flag);
    flash_program(Ota_Bin_Size_Address, Size);
}

/**
 * @brief  Download a file via serial port
 * @param  None
 * @retval None
 */
void SerialDownload(void)
{
    uint8_t Number[10] = "          ";
    int32_t Size = 0;
    char *p = NULL;
    char md5_buf[35] = {0};
    /*
    OTA升级要把串口中断都关掉
    如果定时器频繁中断 可能会影响传输 也要关掉
    */
    //    NVIC_DisableIRQ( LPTIM_IRQn );
    NVIC_DisableIRQ(UART0_IRQn);
    printf("Waiting for the file to be sent ... (press 'a' to abort)\n\r");
    Size = Ymodem_Receive(&tab_1024[0]); // 获得下载升级bin文件的内容
    if (Size > 0)
    {

        printf("\n\n\r Programming Completed Successfully!\n\r--------------------------------\r\n Name: ");
        printf((char *)file_name);
        Int2Str(Number, Size);
        printf("\n\r Size: ");
        printf((char *)Number);
        printf(" Bytes\r\n");
        printf("-------------------\n");
        // 对比文件名
        if ((p = strstr((char *)file_name, "_")) != NULL && ((strstr((char *)file_name, "bin文件名*（根据实际修改）")) != NULL))
        {

            ota_data.size = Size;
            memcpy(ota_data.md5, p + 1, 32);
            GetBinFileMd5(md5_buf);

            if (strcasecmp(md5_buf, ota_data.md5) == 0)
            {
            }
            else
            {
                // md5校验失败
                printf("ota_md5 fail\r\n");
                return;
            }
        }
        else
        {
            printf("file name fail\r\n");
            return;
        }

        set_ota_flag(Size);
        NVIC_SystemReset();
    }
    else if (Size == -1)
    {
        printf("\n\n\rThe image size is higher than the allowed space memory!\n\r");
    }
    else if (Size == -2)
    {
        printf("\n\n\rVerification failed!\n\r");
    }
    else if (Size == -3)
    {
        printf("\r\n\nAborted by user.\n\r");
    }
    else
    {
        printf("\n\rFailed to receive the file!\n\r");
    }
}

/*******************(C)COPYRIGHT 2010 STMicroelectronics *****END OF FILE******/
